package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.interfaces.BTransportModeService;
import cn.huiyunche.base.service.mappers.BTransportModeMapper;
import cn.huiyunche.base.service.model.BTransportMode;
import cn.huiyunche.base.service.model.BTransportModeExample;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @FileName: cn.huiyunche.service.base.tms.interfaces.impl
 * @Description: Description
 * @author: Aaron
 * @date: 2016/11/2 上午11:29
 */
@Service
public class BTransportModeServiceImpl implements BTransportModeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BTransportModeServiceImpl.class);

    @Autowired
    private BTransportModeMapper bTransportModeMapper;

    @Override
    public Integer getIdByConditions(String modeCode, String modeName) {
        LOGGER.info("getIdByName params : {}, {}", modeCode, modeName);
        if (StringUtils.isBlank(modeCode)) {
            LOGGER.error("getIdByName param modeCode must not be null");
            throw new IllegalArgumentException("运输模式编号不能为空");
        }

        //有数据就return，否则新增
        BTransportModeExample example1 = new BTransportModeExample();
        example1.createCriteria().andModeCodeEqualTo(modeCode).andModeNameEqualTo(modeName);
        ;

        BTransportModeExample example2 = new BTransportModeExample();
        example2.createCriteria().andModeCodeEqualTo(modeCode);

        List<BTransportMode> list = bTransportModeMapper.selectByExample(example1);
        if (CollectionUtils.isEmpty(list)) {
            list = bTransportModeMapper.selectByExample(example2);
            if (CollectionUtils.isNotEmpty(list)) {
                BTransportMode transportMode = list.get(0);
                transportMode.setModeName(modeName);
                bTransportModeMapper.updateByPrimaryKeySelective(transportMode);
                return transportMode.getId();
            }
        } else {
            return list.get(0).getId();
        }

        BTransportMode mode = new BTransportMode();
        mode.setModeCode(modeCode);
        mode.setModeName(modeName);
        bTransportModeMapper.insertSelective(mode);
        return mode.getId();
    }
}
